package aop3;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-10 09:36
 * @since JDK 1.6
 */
public class ReflectUtils {

    private Class targetClass;
    private Object target;
    private Method targetMethod;
    private Object[] params;

    @SuppressWarnings("unchecked")
    public ReflectUtils(Object target, String methodName, Object... params) {
        this.target = target;
        this.targetClass = target.getClass();
        this.params = params;
        Class[] cls = new Class[params.length];
        for (int i = 0; i < params.length; i++) {
            cls[i] = params[i].getClass();
        }
        try {
            this.targetMethod = targetClass.getMethod(methodName, cls);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public void invokeMethod() {
        try {
            this.targetMethod.invoke(target, params);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

}
